<script>


  function pyt(x1, y1, x2, y2){
    return Math.sqrt(Math.pow(x1-x2, 2), Math.pow(y1-y2, 2));
  }

  var percentCovered = function (dim1, dim2) {
    // The whole thing is covering the whole other thing
    if (
    (dim1.left <= dim2.left) &&
      (dim1.top <= dim2.top) &&
      ((dim1.left + dim1.width) >= (dim2.left + dim2.width)) &&
      ((dim1.top + dim1.height) > (dim2.top + dim2.height))
  ) {
      return 100;
    }
    // Only parts may be covered, calculate percentage
    else {
      dim1.right		= dim1.left + dim1.width;
      dim1.bottom		= dim1.top + dim1.height;
      dim2.right		= dim2.left + dim2.width;
      dim2.bottom		= dim2.top + dim2.height;

      var l = Math.max(dim1.left, dim2.left);
      var r = Math.min(dim1.right, dim2.right);
      var t = Math.max(dim1.top, dim2.top);
      var b = Math.min(dim1.bottom, dim2.bottom);

      if (b >= t && r >= l) {
        /*	jQuery('<div/>').appendTo(document.body).css({
                                        background:	'red',
                                        position:	'absolute',
                                        left:		l + 'px',
                                        top:		t + 'px',
                                        width:		(r - l) + 'px',
                                        height:		(b - t) + 'px',
                                        zIndex:		100
                                }); */

        var percent = (((r - l) * (b - t)) / (dim2.width * dim2.height)) * 100;

        //	alert(percent + '% covered')

        return percent;
      }
    }
    // Nothing covered, return 0
    return 0;
  };



  var selectBox = jQuery("#highlight");

  var selectElementsInRange = function () {
    var selectBox = jQuery("#highlight");
    if (selectBox.css("display") == "none") {
      return;
    }

    var selectables		= jQuery(".word");
    var selectBoxOffset	= selectBox.offset();
    var selectBoxDim	= {
      left:	selectBoxOffset.left,
      top:	selectBoxOffset.top,
      width:	selectBox.width(),
      height:	selectBox.height()
    };

    selectables.each(function (i) {
      var el			= jQuery(this);
      var elOffset	= el.offset();
      var elDim		= {
        left:	elOffset.left,
        top:	elOffset.top,
        width:	el.width(),
        height:	el.height()
      };

      if (percentCovered(selectBoxDim, elDim) > 0.5) {
        el.addClass("selected");
      }
      else {
        el.css("border", "none");
        el.removeClass("selected");
      }
    });
  };

  jQuery(function(){
    jQuery("#image").mousedown(function(e){
      jQuery("#layer1").fadeOut("slow"); //hide box
      jQuery(".selected").each(function(x){
        jQuery(this).removeClass("selected");
      });
      var y = e.pageY - jQuery(this).offset().top;
      var x = e.pageX - jQuery(this).offset().left;
      var hl = jQuery("#highlight");
      jQuery("#highlight").css("display", "block").css("top", y).css("left", x).css("height", 0).css("width", 0);
    }).mousemove(function(e){
      var y = e.pageY - jQuery(this).offset().top;
      var x = e.pageX - jQuery(this).offset().left;
      var h = y-parseFloat(jQuery("#highlight").css("top"));
      var w = x-parseFloat(jQuery("#highlight").css("left"));
      jQuery("#highlight").css("height", h).css("width", w);
      selectElementsInRange();
    }).mouseup(function(e){
    
      jQuery("#highlight").css("display", "none").css("height", 0).css("width", 0);
      var text = "";
      var ids = [];
      
      
      

      jQuery(".selected").each(function(){
        text += jQuery(this).text() + " ";
        ids.push(jQuery(this).attr("rel"));
      })

      jQuery("#annotationBox").show();
      //jQuery("#selectedText").val(text);
      jQuery("#annotation_highlight").val(text);

      //passes array of ids to hidden form field
      document.myform.tokens.value = ids;

    });

    //retrieve highlighted tokens from database
      var tokenArray = [];
      var annotationArray = [];
      <% @annotations_nopg.each do |at| %>
            tokenArray.push("<%= at.tokens_array %>");
            annotationArray.push("<%=at.id%>");
      <% end %>
        var tokenArraySplit = [];
       
    jQuery.get("/mydocuments/<%= @document.id %>/xml/master.xml_data/pageNum-1.xml", {}, function(xml){
      jQuery(xml).find("PAGE").first().find("TOKEN").each(function(){
        var obj = jQuery(this);
        var x = -1+parseFloat(obj.attr("x"));
        var y = -1+parseFloat(obj.attr("y"));
        var h = 2+parseFloat(obj.attr("height"));
        var w = 2+parseFloat(obj.attr("width"));
        jQuery('<div class="word" rel="' + obj.attr("id") +  '"><p style="display: none">' + obj.text() + '</p></div>').css({left: x, top: y, height: h, width: w, position: "absolute"}).appendTo('#image');

        //highlighting items that have already been annotated to another color
        for(var i=0; i<tokenArray.length; i++){
        tokenArraySplit = tokenArray[i].split(",");
          for(var u=0; u<tokenArraySplit.length; u++){
            if(tokenArraySplit[u] == obj.attr("id")){
              //console.log(annotationArray[i]);
              //jQuery('<div class="loadSelected" rel="' + obj.attr("id") +  '" href="#" style="cursor: pointer;" onclick="setVisible(\'layer1\');return false"><p style="display: none">' + obj.text() + '</p></div>').css({left: x, top: y, height: h, width: w, position: "absolute"}).appendTo('#image');
              jQuery('<div class="loadSelected" id="' + annotationArray[i] + '" rel="' + obj.attr("id") +  '" style="cursor: pointer;"><p style="display: none">' + obj.text() + '</p></div>').css({left: x, top: y, height: h, width: w, position: "absolute"}).appendTo('#image');

            }
          }
       }

      });

      //Loads annotation when user clicks on highlight
      jQuery(".loadSelected").click(function(e){
        //get height and width of message box
        var height = jQuery("#layer1").height();
        var width = jQuery("#layer1").width();

        //calc offset for dis message box
        leftVal = e.pageX-(width/2)+40 + "px";
        topVal = e.pageY-(height/2)+60 +"px";

        var rela = jQuery(this).attr('id');
        var rel = jQuery(this).attr('rel');
        jQuery("#layer1").load("/documents/retrieve_annotation/"+rela, {aid: ""+rel});
        jQuery("#layer1").css({left:leftVal,top:topVal}).show("slow");
      });

      //close show comments box when user clicks outside of box

    }, "xml");    
  });

</script>